#include "medicinequery.h"
#include "ui_medicinequery.h"
#include <QMessageBox>
#include <QJsonArray>

MedicineQueryWindow::MedicineQueryWindow(QWidget *parent)
    : QWidget(parent)
    , medicinequerywindowUi(new Ui::MedicineQueryWindow)
    , networkManager(new NetworkManager(this))
{
    medicinequerywindowUi->setupUi(this);
    connect(networkManager, &NetworkManager::queryMedicineByNameResponseReceived, this, &MedicineQueryWindow::handleQueryMedicineResponse);
    connect(networkManager, &NetworkManager::queryMedicineByCategoryResponseReceived, this, &MedicineQueryWindow::handleQueryMedicineResponse);
    connect(networkManager, &NetworkManager::queryMedicineByKeywordResponseReceived, this, &MedicineQueryWindow::handleQueryMedicineResponse);
}

MedicineQueryWindow::~MedicineQueryWindow()
{
    delete medicinequerywindowUi;
}

void MedicineQueryWindow::on_queryButton_clicked()
{
    medicinequerywindowUi->resultTable->setRowCount(0);
    QString medicineName = medicinequerywindowUi->medicineNameLineEdit->text();
    QString category = medicinequerywindowUi->categoryLineEdit->text();
    QString keyword = medicinequerywindowUi->keywordLineEdit->text();

    if (medicineName.isEmpty() && category.isEmpty() && keyword.isEmpty())
    {
        QMessageBox::warning(this, "输入错误", "每次查询必须填写一个搜索依据。");
        return;
    }

    if ((!medicineName.isEmpty() && !category.isEmpty())
        || (!medicineName.isEmpty() && !keyword.isEmpty())
        || (!category.isEmpty() && !keyword.isEmpty()))
    {
        QMessageBox::warning(this, "输入错误", "每次查询仅可填写一个搜索依据。");
        return;
    }

    QJsonObject json;
    if (!medicineName.isEmpty()) {
        json["name"] = medicineName;
        networkManager->queryMedicineByName(json);
    }
    if (!category.isEmpty()) {
        json["category"] = category;
        networkManager->queryMedicineByCategory(json);
    }
    if (!keyword.isEmpty()) {
        json["keyword"] = keyword;
        networkManager->queryMedicineByKeyword(json);
    }
}

void MedicineQueryWindow::handleQueryMedicineResponse(const QJsonObject &response)
{
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();

    if (code == 200) {
        QString dataString = response.value("data").toString();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(dataString.toUtf8());

        if (jsonDoc.isObject()) {
            QJsonObject data = jsonDoc.object();
            qDebug() << "Data object:" << QJsonDocument(data).toJson(QJsonDocument::Indented);
            displayData(data);
        } else if (jsonDoc.isArray()) {
            QJsonArray dataArray = jsonDoc.array();
            qDebug() << "Data array:" << QJsonDocument(dataArray).toJson(QJsonDocument::Indented);
            for (const QJsonValue &value : dataArray) {
                if (value.isObject()) {
                    displayData(value.toObject());
                }
            }
        } else {
            qDebug() << "Failed to parse 'data' as JSON object or array.";
            return;
        }
    } else {
        QMessageBox::warning(this, "错误", "药品查询失败：" + desc);
    }
}

void MedicineQueryWindow::displayData(const QJsonObject &data)
{
    int row = medicinequerywindowUi->resultTable->rowCount();
    medicinequerywindowUi->resultTable->insertRow(row);

    setTableItem(row, 0, QString::number(data.value("id").toInt()));
    setTableItem(row, 1, data.value("name").toString());
    setTableItem(row, 2, data.value("category").toString());
    setTableItem(row, 3, data.value("supplier").toString());
    setTableItem(row, 4, QString::number(data.value("price").toDouble()));
    setTableItem(row, 5, QString::number(data.value("stock").toInt()));
    setTableItem(row, 6, QString::number(data.value("threshold").toInt()));
    setTableItem(row, 7, QString::number(data.value("validity").toInt()));
}

void MedicineQueryWindow::setTableItem(int row, int column, const QString &text)
{
    medicinequerywindowUi->resultTable->setItem(row, column, new QTableWidgetItem(text));
}
